
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;

public class PrintWithUI extends javax.swing.JApplet {

    private URL url;
    private javax.swing.JPanel pnlMain;
    private javax.swing.JButton btnPrint;

    @Override
    public void init() {
        try {
            initComponents();
            url = new URL(getCodeBase(), getParameter("REPORT_URL"));
        } catch (MalformedURLException ex) {
            ex.printStackTrace(System.out);
        }

    }

    private void initComponents() {
        pnlMain = new javax.swing.JPanel();
        btnPrint = new javax.swing.JButton();
        btnPrint.setText("Print the Report");
        btnPrint.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        pnlMain.add(btnPrint);
        getContentPane().add(pnlMain, java.awt.BorderLayout.WEST);

    }

    protected void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {

        BufferedReader bf = null;
        try {
            InputStream in = url.openStream();
            bf = new BufferedReader(new InputStreamReader(in));
        } catch (IOException ex) {
            ex.printStackTrace(System.out);
        }

        if (bf == null) {
            System.out.println("Input Stream not available");
            return;
        }
        DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc myDoc = new SimpleDoc(bf, psInFormat, null);
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);
        PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
        PrintService myPrinter = ServiceUI.printDialog(null, 0, 0, services, defaultService, psInFormat, aset);
        if (myPrinter != null) {
            DocPrintJob job = myPrinter.createPrintJob();

            try {
                job.print(myDoc, aset);

            } catch (Exception pe) {
                pe.printStackTrace(System.out);
            }
        } else {
            System.out.println("no printer services found");

        }
        

    }
}
